<template>
	<view class="upload-photo">
		<view class="upload-main" :style="card_photo_url?'padding:0rpx':''">
			<image :src="card_photo_url?card_photo_url:cover" class="cover" mode="aspectFill" />
			<view class="upload-btn" @click="upload">
				<i class="iconfont icon-camera icon" />
			</view>
		</view>
		<view class="label">
			{{label}}
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, Ref, defineProps, defineEmits } from "vue";
	import { COVER_TYPE } from './types';
	import { useToken } from '@/hooks/useToken';
	import { baseUrl } from '@/http';
	
	interface IProps {
		cover : COVER_TYPE,
		label ?: string,
	}

	const emit = defineEmits(['update:modelValue'])

	const props = withDefaults(defineProps<IProps>(), {
		cover: COVER_TYPE.IDCARD_FRONT,
	})

	const card_photo_url : Ref<string> = ref('');

	const { getTokenSync, removeTokenSync } = useToken();

	const upload = () => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			success: async (res) => {
				const token = getTokenSync();
				uni.showLoading({})

				console.log('res.tempFilePaths[0]=======>', res.tempFilePaths[0])
				let options : UniApp.UploadFileOption;
				const success = async (res : UniApp.UploadFileSuccessCallbackResult) => {
					const result = JSON.parse(res.data);
					if (result.status === 200) {
						card_photo_url.value = result.data.file_url;
						emit('update:modelValue', card_photo_url.value);
					} else if (result.status == -2) {
						uni.prompt.$showToast('上传的图片不能超过2M');
					} else {
						uni.prompt.$showToast('上传图片失败');
					}
					uni.hideLoading();
				};

				const fail = () => {

					uni.prompt.$showToast('上传图片失败');
					uni.hideLoading();
				}


				// #ifdef H5
				options = {
					url: `${baseUrl.value}/upload/uploadImagesCos`,
					file: res.tempFiles[0],
					header: {
						"Authorization": 'Bearer' + token,
					},
					success,
					fail
				}
				// #endif

				// #ifdef MP-WEIXIN
				options = {
					url: `${baseUrl.value}/upload/uploadImagesCos`,
					filePath: res.tempFilePaths[0],
					header: {
						"Authorization": 'Bearer' + token,
						'Content-Type': 'application/x-www-form-urlencoded',
					},
					name: "file",
					fileType: 'image',
					success,
					fail
				}
				// #endif

				uni.uploadFile(options)
			}
		});
	}
</script>

<style scoped lang="scss">
	@import "./uploadPhoto.scss";
</style>